package com.yaolaizaixian.merchant.home;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.CreadOrderModel;
import com.yaolaizaixian.merchant.bean.OrderLsm;
import com.yaolaizaixian.merchant.bean.ShopBili;
import com.yaolaizaixian.merchant.order.PayCodeActivity;
import com.yaolaizaixian.merchant.utils.AppManager;
import com.yaolaizaixian.merchant.utils.CashierInputFilter;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.MyUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/4/26.
 * 创建订单页
 */
public class CreateOrderActivity extends BaseActivity {

    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.et_order_money)
    EditText etOrderMoney;
    @BindView(R.id.tv_order_jinbi)
    TextView tvOrderJinbi;
    @BindView(R.id.ll_top)
    AutoLinearLayout llTop;
    @BindView(R.id.tv_wenxintishi)
    TextView tvWenxintishi;
    @BindView(R.id.rl_order_erweima)
    AutoRelativeLayout rlOrderErweima;
    @BindView(R.id.head)
    TextView head;
    @BindView(R.id.tv_fanlibaifenbi)
    TextView tvFanlibaifenbi;
    private String shopsysno;
    private String usersysno;
    private String vendorsysno;
    private String TAG = "CreateOrderActivity";
    private Dialog progressDialog;
    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;

                    LogUtil.LogShitou(TAG, result);

                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);

                    if (baseModel.isFlag()) {

                        progressDialog.dismiss();

                        CreadOrderModel creadOrderModel = GsonUtil.jsonToBean(result, CreadOrderModel.class);
                        OrderLsm orderLsm = creadOrderModel.getData().getLsm();
                        //订单id
                        String sysno = orderLsm.getSysno();
                        Intent intent1 = new Intent(CreateOrderActivity.this, PayCodeActivity.class);
                        intent1.putExtra("sysno", sysno);
                        intent1.putExtra("money", etOrderMoney.getText().toString().trim());
                        startActivity(intent1);

                    } else {

                        progressDialog.dismiss();
                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {

                            showConflictDialog(CreateOrderActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(CreateOrderActivity.this, "您的账号在其它设备登录");

                        } else {

                            Toast.makeText(CreateOrderActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT).show();

                            return;

                        }
                    }

                    break;


                //获取店铺返金币比例
                case 2:

                    String result1 = (String) msg.obj;
                    LogUtil.LogShitou(TAG, "返金币比例：" + result1);
                    BaseModel baseModel1 = GsonUtil.jsonToBean(result1, BaseModel.class);
                    if (baseModel1.isFlag()) {
                        ShopBili shopBili = GsonUtil.jsonToBean(result1, ShopBili.class);
                        final String bili = shopBili.getData().getCoinRebate();

                        tvFanlibaifenbi.setText("金币返利  "+bili+"%");

                        if (!TextUtils.isEmpty(bili) && !bili.equals("0")) {
                            etOrderMoney.addTextChangedListener(new TextWatcher() {
                                @Override
                                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                }

                                @Override
                                public void onTextChanged(CharSequence s, int start, int before, int count) {

                                }

                                //文本输入之后
                                @Override
                                public void afterTextChanged(Editable s) {

                                    if (!TextUtils.isEmpty(s)) {

                                        Double a = Double.valueOf(s.toString()) * (Double.valueOf(bili) * 0.01);
                                        //保留两位小数以后
                                        tvOrderJinbi.setText("¥ " + MyUtils.formatDouble3(a).toString());

                                    } else {

                                        tvOrderJinbi.setText("¥ 0");
                                    }

                                }
                            });
                        }

                    }

                    break;
            }
        }
    };


    @Override
    public void initView() {

        setContentView(R.layout.activity_createorder);
    }

    @Override
    public void initData() {


        tvTitleText.setText("收单页");
        InputFilter[] filters = {new CashierInputFilter()};
        etOrderMoney.setFilters(filters);


        //店铺id
        shopsysno = SharedPreferencesUtil.getString(getApplicationContext(), "shopsysno", "");

        Log.e(TAG, "init店铺" + shopsysno);

        //员工id
        usersysno = SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", "");
        //商户id
        vendorsysno = SharedPreferencesUtil.getString(getApplicationContext(), "vendorsysno", "");

        getShopBili();

    }


    //获取店铺金币比例(只获取比例，不显示返回的值)
    private void getShopBili() {

        try {

            //用户id
            HashMap<String, String> sortedParams = new HashMap<String, String>();
            final String url = BaseInfo.URL + "shopping/shoppingCoinRate.do";
            // sysNo 值  3des加密
            //店铺ID
            sortedParams.put("shopStoreSysno", shopsysno);
            Log.e(TAG, "店铺ID" + shopsysno);
            sortedParams.put("price", "100");
            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, this))
                    .build()
                    .execute(new MyStringCallback1());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

        AppManager.getAppManager().addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        AppManager.getAppManager().finishActivity(this);
    }

    @OnClick({R.id.ll_back, R.id.rl_order_erweima})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_back:

                finish();

                break;

            case R.id.rl_order_erweima:

                String money = etOrderMoney.getText().toString().trim();

                if (!TextUtils.isEmpty(money)) {

                    getData(money);
                    showdia();

                } else {

                    Toasty.error(CreateOrderActivity.this, "请输入订单金额", Toast.LENGTH_SHORT, true).show();

                }

                break;
        }
    }

    //订单入库
    private void getData(String money) {

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();

            final String url = BaseInfo.URL + "lifeOrderController/shopPlaceOrderV2.do";
            // sysNo 值  3des加密
            //店铺ID
            sortedParams.put("shopSysno", shopsysno);
            //员工ID
            sortedParams.put("employeeSysno", usersysno);
            //商户id
            sortedParams.put("vendorSysno", vendorsysno);
            //金额
            sortedParams.put("totalAmt", money);

            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, this))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {
            progressDialog.dismiss();
            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }
    }


    class MyStringCallback1 extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 2;
            message.obj = response;
            mhandler.sendMessage(message);
        }
    }

    //展示正在加载
    private void showdia() {

        progressDialog = new Dialog(CreateOrderActivity.this, R.style.progress_dialog);
        progressDialog.setContentView(R.layout.dialog);
        progressDialog.setCancelable(true);
        progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        TextView msg = (TextView) progressDialog.findViewById(R.id.id_tv_loadingmsg);
        msg.setText("正在生成收款二维码,请稍候");
        progressDialog.show();

    }

}
